<?php
/**
 * 《采购申请》实现类
 *
 * @author 孙晓晔
 * @version $Id: Purchase.class.php 1061 2010-04-09 08:31:55Z sunxy $
 */
require_once(dirname(__FILE__) . '/Bom.class.php');

class Purchase extends Bom {
	public $name = '采购信息';
	public $tbl = Constant::tbl_wl_purchase;

	public $type = array(
		// '-' => '请选择',
		'预付20%' => '预付20%',
		'预付30%' => '预付30%',
		'预付50%' => '预付50%',

		'预付全款' => '预付全款',			
		'货到付款' => '货到付款',
	
		'当月结算' => '当月结算',
		'月结30天' => '月结30天',
		'月结60天' => '月结60天',
		'月结90天' => '月结90天',

		'其它' => '其它',
	);

	public $status = array(
		'-' => '请选择',
		'1' => '等待审核',
		'2' => '等待采购',
		'3' => '正在采购',
		'4' => '等待送货',

		// '5' => '暂停采购',
		'6' => '取消采购',

		'8' => '等待入库',
		'9' => '完成采购',

		'19' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'emp' => '采购员',

		'supplier' => '供应商',
		'number' => '送货单',
		'date' => '交货日期',

		'status' => '状态',
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',	
		'emp' => '采购员',
		'supplier' => '供应商',
		'currency' => '币种',

		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('type_option', $this->type);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 month'));
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '采购员',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'material/in/purchase/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'number') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['number'];
		}

		if ($px == 'date') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['date'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function xls($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$mold_s = $this->_input($request['mold_s']);
		
		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s LIMIT 80";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		
		if (empty($mold_s)) {
			$fmt = "SELECT * FROM %s a %s %s";
			$sql = sprintf($fmt, $this->tbl, $where, $orderby);			
		} else {
			$fmt = "SELECT a.* FROM %s a, %s b %s GROUP BY id %s ";
			$sql = sprintf($fmt, $this->tbl, Constant::tbl_wl_record_in, $where, $orderby);
		}
		
		// $sql = sprintf($fmt, $this->tbl, $where, $orderby);
		// debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row['num_'] = $this->_num($row['id']);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/in/purchase');
		return true;
	}
	
	function xls_record($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$request['tpl'] = "xls";
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);

			$row['record'] = $this->record_in($row['id']);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/in/purchase_record');
		return true;
	}

	function _where($request) {
		$code_s = $request['code_s'];
		
		$mold_s = $this->_input($request['mold_s']);
		$number_s = $request['number_s'];
		// $type_s = $request['type_s'];

		$date1_s = $this->_input($request['date1_s']);
		$date2_s = $this->_input($request['date2_s']);
		
		$emp_t_s = $request['emp_t_s'];
		if ($emp_t_s == 'emp') {
			$request['emp_s'] = $request['emp_a_s'];
		} else if ($emp_t_s == 'oper') {
			$request['oper_s'] = $request['emp_a_s'];
		}

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		if (!empty($mold_s)) {
			$where .= " AND a.id = b.purchase AND b.mold = '" . $mold_s . "'";
		}

		if (!empty($code_s)) {
			$where .= " AND code = '" . $code_s . "'";
		}

		if (!empty($number_s)) {
			$where .= " AND number = '" . $number_s . "'";
		}
		
		$where .= $this->_where_x("type", $request['type_s']);

		if (!empty($payment_s)) {
			$where .= " AND payment = '" . $payment_s . "'";
		}

		if (!empty($date1_s)) {
			$where .= " AND date >= '" . $date1_s . "'";
		}

		if (!empty($date2_s)) {
			$where .= " AND date < '" . $date2_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}
	
		if ($this->_audit('60') || $this->_audit('68')) {
			return ' visible = 1';
		}
	
		$emp = $_SESSION['id'];
	
		return sprintf(" (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);
		
		$mold_s = $this->_input($request['mold_s']);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		
		if (empty($mold_s)) {
			$fmt = "SELECT * FROM %s a %s %s";
			$sql = sprintf($fmt, $this->tbl, $where, $orderby);			
		} else {
			$fmt = "SELECT a.* FROM %s a, %s b %s GROUP BY id %s ";
			$sql = sprintf($fmt, $this->tbl, Constant::tbl_wl_record_in, $where, $orderby);
		}
		
		debug($sql);
		
		// $sql = sprintf($fmt, $this->tbl, $where, $orderby);
		// debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row['num_'] = $this->_num('purchase', $row['id']);
				// $row['color'] = $this->_status_color($row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'material/in/purchase/list');
		return true;
	}

	function _status_color($row) {
		$status = $row['status'];

		if ($status > 8 || $status == 5 || $status == 6) {
			return '';
		}

		$b1 = time() > strtotime($row['date']) ? true : false;
		
		if ($b1) {
			if ($status < 4) {
				return 'red';
			} else {
				return 'yellow';
			}
		}

		return '';
	}

	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($row['status'] > 2) {
			return false;
		}

		if ($this->_audit('77')) {
			return true;
		}

		$emp = $_SESSION['id'];
		
		if ($row['emp'] == $emp || $row['oper'] == $emp) {
			return true;
		}

		return false;
	}
	
	function _num($field, $id) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
	
		return $aa->_count($field, $id);
	}
	
	function _total2($field, $id) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
	
		return $aa->_total2($field, $id);
	}

	function _total($id) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		return $aa->_total($id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function clean($controller, $request) {
		$cart = $_SESSION['cart'];

		$id = $request['material'];
		$data = array();
		while (list($k, $v) = each($cart)) {
			if ($k == $id) {
				continue;
			}

			$data[$k] = $k;
		}

		$_SESSION['cart'] = $data;

		$this->add($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('3 day'));
		
		$controller->assign_by_ref('tecmold_option', $this->tecmold());

		$cart = $_COOKIE['cart'];
		if (empty($cart)) {
			$controller->display($request, 'material/in/purchase/new');
			return true;
		}

		// echo $cart;
		$a = json_decode($cart);
		// print_r($a);

		$data = array();
		while (list($k, $v) = each($a)) {
			$row = $this->id(Constant::tbl_material, $v[0]);

			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'material/in/purchase/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function purchasePost($controller, $request) {
		$this->pretreat($controller);

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$customer = $this->_input($request['customer']);
		$customer_x = addslashes($request['customer_x']);
		
		$name = addslashes($request['name']);
		$date = $request['date'];
		
		$address = addslashes($request['address']);
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(customer, customer_x, emp, date, name, address, content, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $customer, $customer_x, $emp, $date, $name, $address, $content, $_SESSION['id']);
		debug($sql);
		$db->query($sql);

		$purchase = $db->insert_id();
		
		$id = $request['id'];
				
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		if ($aa->_insert_bom($id, $purchase)) {
			$this->_status_bom($id, "3");
		}

		return true;
	}
	
	function _status_bom($id, $status) {
		require_once(dirname(__FILE__) . '/Bom.class.php');
		$aa = new Bom();
		$aa->_status($id, $status);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$customer = $this->_input($request['customer']);
		$customer_x = addslashes($request['customer_x']);
		
		$name = addslashes($request['name']);
		$date = $request['date'];
		$address = addslashes($request['address']);
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, emp, customer, customer_x, date, name, address, content, oper, createtime, modifytime) ";
		$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $emp, $customer, $customer_x, $date, $name, $address, $content, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);

		$id = $db->insert_id();
		
		$request['id_s'] = $id;

		$cart = $_COOKIE['cart'];
		if (empty($cart)) {
			$controller->assign('baseLink', $this->doGet($request, 'findPost'));
			$this->findPost($controller, $request);
			return true;
		}

		// echo $cart;
		$a = json_decode($cart);
		// print_r($a);

		$fmt = "INSERT INTO %s(purchase, material, name, standard, unit, price, tax, pay, amount, emp, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		while (list($k, $v) = each($a)) {
			$row = $this->id(Constant::tbl_material, $v[0]);
			if (isset($v[1])) {
				$row['price'] = $v[1];
			}

			if (isset($v[2])) {
				$amount = $v[2];
			} else {
				$amount = 1;
			}

			$sql = sprintf($fmt, Constant::tbl_wl_record_in, $id, $row['id'], $row['name'], $row['standard'], $row['unit'], $row['price'], '0', $row['price'], $amount, $emp);
			$db->query($sql);
			// debug($sql);
		}
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 * 开始采购
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function start($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$status = '3';

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		// debug($sql);
		$db->query($sql);

		$this->_record_in_status($id, $status);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function finish($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$status = '8';

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		// debug($sql);
		$db->query($sql);

		$this->_record_in_status($id, $status);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	

	function _code() {
		$ret = '';
		$dd = sprintf("%s", date('ymd00'));

		do {
			$dd++;
			$dd = sprintf("%08d", $dd);
			$ret = "T" . $dd;
		} while ($this->_code_exist($ret));

		return $ret;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$row['exchange'] = $this->_exchange($row['currency']);
		// $row['log'] = json_encode($this->_record_in2($id));
		
		$row['item'] = json_encode($this->_edit_item($row['id']));
		
		$controller->assign_by_ref('result', $row);
		
		$controller->assign_by_ref('tecmold_option', $this->tecmold());

		$controller->display($request, 'material/in/purchase/edit');
		return true;
	}
	
	function _record_in2($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		return $aa->_list2($id);		
	}
	
	function _edit_item($id) {
		$a = $this->_record_in($id);
	
		$data = array();
		while (list($k, $v) = each($a)) {
			$t = array();
	
			$t['id'] = $v['id'];
			$t['name'] = $v['name'];
			$t['standard'] = $v['standard'];
			
			$t['amount2'] = $v['amount2'];
			$t['unit2'] = $v['unit2'];
			$t['price2'] = $v['price2'];
			$t['total'] = $v['total'];
			
			$t['amount'] = $v['amount'];
			$t['unit'] = $v['unit'];
			
			$t['mold_'] = $v['mold_'];
			
			$t['content'] = $v['content'];
			$t['createtime'] = $v['createtime'];
			$t['status_t'] = $v['status_t'];
			$t['ok'] = $v['ok'];
	
			$data[] = $t;
		}
	
		return $data;
	}
	
	function _record_in($id, $status = 'all') {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
	
		return $aa->_list2($id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$customer = $this->_input($request['customer']);
		$customer_x = addslashes($request['customer_x']);
		
		$name = addslashes($request['name']);
		$date = $request['date'];
		$address = addslashes($request['address']);
		$content = addslashes($request['content']);

		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$currency = $request['currency'];
		$type = addslashes($request['type']);
		$tax = $request['tax'];
		
		$total = $request['total'];
		
		// $total = $this->_total($id);
		
		$rate = $this->_exchange($request['currency']);
		$rmb = $total * $rate;
		
		$this->_update_item($request);
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET office = '%s', emp = '%s', date = '%s', customer = '%s', customer_x = '%s', supplier = '%s', supplier_x = '%s', name = '%s', ";
		$fmt .= "address = '%s', currency = '%s', total = '%s', rate = '%s', rmb = '%s', type = '%s', tax = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $emp, $date, $customer, $customer_x, $supplier, $supplier_x, $name, $address, $currency, $total, $rate, $rmb, $type, $tax, $content, $id);
		debug($sql);
		$db->query($sql);
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _update_item($request) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
	
		$aa->_update($request);
		
		// $aa->_update_supplier($request);
	}
	
	function _update_record_in($id, $log, $emp) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		return $aa->_update($id, $log, $emp);
	}
	
	function upload($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
	
		$this->_files_clean($id);
	
		$row = $this->_view($id);
	
		$controller->assign_by_ref('result', $row);
	
		$controller->display($request, 'material/in/purchase/upload');
		return true;
	}

	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$record_in = $this->record_in($id);
		$controller->assign_by_ref('record_in', $record_in);

		$len = count($record_in);
		if ($len > 11) {
			$blank = array();
		} else {
			$blank = range(1, 12 - $len , 1);
			$controller->assign_by_ref('blank', $blank);
		}
		
		if ($request['view'] == '2') {
			$controller->display($request, 'material/in/purchase/view_2');
		} else {
			$controller->display($request, 'material/in/purchase/view');
		}
		
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['customer_t'] = Name::customer_code($row['customer']);
		$row['customer_x'] = json_decode($row['customer_x']);
		
		$row['supplier_x'] = json_decode($row['supplier_x']);

		$row['files'] = $this->_files($row['id']);
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function test($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$record_in = $this->record_in($id);
		$controller->assign_by_ref('record_in', $record_in);

		$len = count($record_in);
		if ($len > 11) {
			$blank = array();
		} else {
			$blank = range(1, 12 - $len , 1);
			$controller->assign_by_ref('blank', $blank);
		}

		$controller->display($request, 'material/in/purchase/test');
		return true;
	}

	function verify($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->assign_by_ref('record_in', $this->record_in($id));

		$controller->display($request, 'material/in/purchase/verify');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function verifyPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$content = addslashes($request['content']);
		$status = $request['status'];

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = %s";
		$sql = sprintf($fmt, $this->tbl, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$this->_record_in_status($id, $status);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function ajax_a($controller, $request) {
		$id = $_COOKIE['id_'];
		$data = array();
		if (!$this->ajax_a_($id)) {
			$data['status'] = 2;
		} else {
			$data['status'] = 1;
		}

		$controller->assign('result', json_encode($data));

		$request['tpl'] = 'json';
		$controller->display($request, 'json');
		return true;
	}

	function ajax_a_($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			if ($row['emp'] == $_SESSION['id']) {
				return true;
			}
		}

		return false;
	}
	
	function record_in($id) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		return $aa->_list($id);
	}		

	function status($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$status = $request['status'];		

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		// debug($sql);
		$db->query($sql);
		
		$this->_record_in_status($id, $status);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	
	function _update_status($id, $status) {
	
		clean($this->tbl . "_id_" . $id);
	
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		// debug($sql);
		$db->query($sql);
	
		// $this->_record_in_status($id, $status);
	
		return true;
	}

	function in($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		$data = $aa->_list2($id);

		$controller->assign_by_ref('record_in', $data);

		$controller->display($request, 'material/in/purchase/in');
		return true;
	}

	/**
	 * 采购入库
	 */
	function inPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		if ($aa->_in_purchase($request)) {
			$db = newdb($this->dsn_w);
			$fmt = "UPDATE %s SET status = '9', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	/**
	 * 指定供应商
	 */
	function supplier($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->assign_by_ref('record_in', $this->record_in($id));

		$controller->display($request, 'material/in/purchase/supplier');
		return true;
	}

	/**
	 * 指定供应商
	 */
	function supplierPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$currency = $request['currency'];		
		$type = addslashes($request['type']);
		$tax = $request['tax'];
		$total = $this->_total($id);
		
		$rate = $this->_exchange($request['currency']);
		$rmb = $total * $rate;
		
		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET supplier = '%s', supplier_x = '%s', currency = '%s', rate = '%s', rmb = '%s', type = '%s', tax = '%s', total = '%s', content = concat(content, '\n%s'), modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $supplier, $supplier_x, $currency, $rate, $rmb, $type, $tax, $total, $content, $id);
		debug($sql);
		$db->query($sql);
		
		$this->_update_supplier($request);
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _update_supplier($request) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		
		$aa->_update_supplier($request);
	}
	
	/**
	 * 下单
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function po($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);
		
		$controller->assign_by_ref('record_in', $this->record_in($id));

		$controller->display($request, 'material/in/purchase/po');
		return true;
	}

	/**
	 * 下单
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function poPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$content = addslashes($request['content']);
		
		$rate = $this->_exchange($request['currency']);
		$rmb = $total * $rate;
		
		$total = $this->_total($id);
		$status = "4";
		
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();
		if ($aa->_is_po($id)) {
			$aa->_status_puchase($id, $status);

			$db = newdb($this->dsn_w);
			$fmt = "UPDATE %s SET total = '%s', rate = '%s', rmb = '%s', content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $total, $rate, $rmb, $content, $status, $id);
			debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function reason($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->assign_by_ref('record_in', $this->record_in($id));

		$controller->display($request, 'material/in/purchase/reason');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function reasonPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$content = addslashes($request['content']);
		$status = $request['status'];		

		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET content = concat(content, '%s'), status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $content, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}

		$this->_record_in_status($id, $status);
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function out($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$row['amount'] = $row['total'];
		$row['type'] = '12';

		$controller->assign_by_ref('result', $row);
		
		require_once(dirname(__FILE__) . '/../finance/OutMy.class.php');
		$aa = new OutMy();
		
		$aa->add($controller, $request);
	}
	
	function outPost($controller, $request) {
		require_once(dirname(__FILE__) . '/../finance/OutMy.class.php');
		$aa = new OutMy();
		
		$out = $aa->_add($controller, $request);
		
		$id = $request['id'];
		
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET `out` = '%s' WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $out, $id);
		debug($sql);
		$db->query($sql);
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}

			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}
			
			$this->_delete3($id);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2, modifytime = NOW() WHERE id = '%s'";
		}
	
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}

	function _delete($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		$result = $db->query($sql);
		// debug($sql);
		if ($row = $db->fetch_array($result)) {
			if ($row['status'] < 3 && $row['emp'] == $_SESSION['id']) {
				return false;
			}

			return true;
		}

		return true;
	}
	
	function _ss_status($id, $status) {
		$this->_record_in_status($id, $status);
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		$num = array(
			'1' => '按次数',
			'2' => '按金额',
		);
		$controller->assign('num_option', $num);

		$controller->assign('t1', strtotime('-1 month'));
		// $controller->assign('t2', strtotime('+1 day'));

		$controller->display($request, 'material/in/purchase/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(total) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(total) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	function _record_in_status($purchase, $status) {
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$aa = new RecordIn();

		$aa->_status_puchase($purchase, $status);
	}
	
	function _list() {
		$emp = $_SESSION['id'];
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE createtime > DATE_ADD(NOW(), INTERVAL -2 MONTH) AND status < 4 AND (emp = '%s' OR oper = '%s') ORDER BY id DESC";
		$sql = sprintf($fmt, $this->tbl, $emp, $emp);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$ret[] = $row;
		}

		return $ret;
	}
	
	function t($controller, $request) {

		echo $this->_code();
	}
	
	function tj3($controller, $request) {
		
		$bb = $this->_list_email('355');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
	
		$from = $this->email;
		$subject = '采购信息';
	
		$data = $this->emp_dept('cg');
		
		$dd = " createtime > DATE_ADD(now(), INTERVAL -90 DAY) AND date < DATE_ADD(now(), INTERVAL 1 DAY)";
		while (list($emp, $name) = each($data)) {
			$a = Common::emp($emp);
			if (empty($a['email']) || $a['status'] == '3') {
				continue;
			}
			
			$to = $a['email'];
			
			$ww = sprintf(" emp = '%s' AND %s AND status < 9", $emp, $dd);
			
			$cc = array(
				'可能有延后的采购'=>array('w' => $ww, 'b'=>'supplier, status'),
				// '新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
				// '更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),
			);
			
			if ($this->_tj_cc($controller, $cc)) {
				echo "222";
				continue;
			}
			
			$body = $this->_tj_html($controller, $request, 'material/in/purchase/tj_list_a');
			
			$this->mail_html($from, $to, $subject, $body);
			
			$this->_tj_mail($from, $bb, $subject, $body);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('313');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '采购信息';
		
		$cc = array(
			'完成采购'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND status = 9", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}
		
		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'material/in/purchase/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}

	function tjw($controller, $request) {
		$bb = $this->_list_email('313');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$this->pretreat($controller);

		$from = $this->email;
		$subject = '采购信息（周报）';
		
		$cc = array(
			'完成采购'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND status = 9", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'material/in/purchase/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'currency';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(total*rate) AS c, SUM(total) AS d FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(total*rate) AS c, SUM(total) AS d FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}

	function t_total($controller, $request) {
		$db = newdb($this->dsn);
		$fmt = "SELECT * FROM %s WHERE status > 3";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$total = $this->_total($row['id']);

			$fmt = "UPDATE %s SET total = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $total, $row['id']);
			echo $sql . "\n";
			$db->query($sql);

			echo ".";
		}

		logdate($controller, $request);
		return true;
	}
	
	function _update_total($id, $total) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET total = '%s' WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $total, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function z($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE supplier_x is NULL";
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$supplier_x = $this->_supplier_x($row['supplier']);			
			
			$fmt = "UPDATE %s SET supplier_x = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $supplier_x, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function x($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s ORDER BY id DESC";
		// $fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$supplier_x = $this->_x($row['supplier'], $row['supplier_x']);
			
			$fmt = "UPDATE %s SET supplier_x = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $supplier_x, $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function _x($id, $supplier_x) {
		$j = json_decode($supplier_x);
		
		// var_dump($j);
		
		require_once(dirname(__FILE__) . '/../contact/Supplier.class.php');
		$aa = new Supplier();
		
		$c = $aa->_view($id);
				
		$ret['name'] = $c['name'];
		$ret['fullname'] = $c['fullname'];
		$ret['address'] = $c['address'];
		$ret['web'] = $c['url'];
		
		if (empty($j->contact)) {
			$ret['contact'] = $j->name;
		} else {
			$ret['contact'] = $j->contact;
		}
		
		$ret['mobile'] = $j->mobile;
		$ret['tel'] = $j->tel;
		$ret['fax'] = $j->fax;
		$ret['email'] = $j->email;		
		$ret['content'] = $j->content;
		
		$ret = json_encode($ret);
		
		return addslashes($ret);
	}
	
	function _supplier($supplier) {
		$dd = date('Y-m-d', strtotime("-18 MONTH"));
	
		$db = newdb($this->dsn_r);
		$fmt = "SELECT COUNT(*) t FROM %s WHERE supplier = '%s' AND createtime > '%s'";
		$sql = sprintf($fmt, $this->tbl, $supplier, $dd);
		// echo $sql . "\n";
		$result = $db->query($sql);
		$row = $db->fetch_array($result);
		if ($row['t'] > 0) {
			return true;
		}
	
		return false;
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s' AND status < 8";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	
		require_once(dirname(__FILE__) . '/RecordIn.class.php');
		$recordin = new RecordIn();
		$recordin->move($from, $to);
	}
	
	function ajax_emp($controller, $request) {
		$item = $request['item'];
		
		$id = $_COOKIE['id_'];
		$ret = array();
	
		if ($this->_ajax_x($id, 'emp')) {
			$ret['status'] = 1;
		} else if ($this->_ajax_x($id, 'oper')) {
			$ret['status'] = 1;
		} else if ($this->_audit($item)) {
			$ret['status'] = 1;
		} else {
			$ret['status'] = 2;
		}
		
		echo json_encode($ret);
	}
	
	function view_supplier($controller, $request) {
		$id = $request['id'];
	
		$ret = $this->_list_supplier($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'material/in/purchase/_list_c');
		return true;
	}
}
?>
